//
//  ReaderFileViewController.m
//  Reader
//
//  Created by Kiran Panesar on 15/10/2014.
//
//

#import "ReaderFileViewController.h"
#import "ReaderViewController.h"
#import "UIViewController+WSJLodingView.h"
#import "UIImage+SQExtension.h"

#import "JCDownloader.h"
//#import "JFFileManager.h"
#import "JCAlertView.h"

#import "AppDelegate.h"
#import <UMMobClick/MobClick.h>
#import "CKHttpCommunicate.h"
#import "HELPDFfileCacheTool.h"
#import "WSJPopview.h"

@interface ReaderFileViewController () <UIAlertViewDelegate>


@property (nonatomic,  strong) JCDownloadOperation *operation;


@property (nonatomic,  assign) NSInteger studiedSeqNum;

@property (nonatomic,  strong) NSURLSessionDownloadTask *downTask;

@property (nonatomic,  strong) MBProgressHUD *bar;


@end

@implementation ReaderFileViewController

#pragma mark ReaderViewControllerDelegate

- (void)dismissReaderViewController:(ReaderViewController *)viewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(0, 0, 16, 28);
    [btn setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
//    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back =[[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.leftBarButtonItem = back;
   [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:kMainColor] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    [[UINavigationBar appearance] setTintColor:kMainColor];
    [self downPdfFile];
    
//// 没有网络的时候
//    weakSelf_define;
//    HELNetworkStatus statues =[HELNetworkManager sharedMg].netStatus;
//    if (statues == 0) {
//        NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:self.pdfModel.fileName isMP4:NO];
//        if (filePath) {
//            
//            NSNumber *page =  [HELPDFfileCacheTool getLastPageFromKey:self.pdfModel.fileName];
//            if (page) {
//                self.studiedSeqNum =[page integerValue];
//            }else{
//                self.studiedSeqNum = 1;
//            }
//            
//            [self preparePdfWithFilePath:filePath];
//            return ;
//        }else{
//          
//            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"当前pdf并未缓存在本地" ButtonType:1 ButtonTitle:@"返回" Click:^{
//                [weakSelf dismissViewControllerAnimated:YES completion:nil];
//            }];
//        }
//        return;
//    }
    
    // 网络正常直接请求进度
    
   
}


- (void)backAction{
    
//    weakSelf_define;
    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否确认退出并保存进度" delegate:self cancelButtonTitle:@"继续学习" otherButtonTitles:@"退出并保存",nil];
    [alerView show];
   

  
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex ==1) {
        if (self.downTask && self.downTask.state ==NSURLSessionTaskStateRunning) {
            [self.downTask cancel];
           
        }
        weakSelf_define;
      [self dismissViewControllerAnimated:YES completion:^{
          if (_readerViewController) {
              if (weakSelf.callBack) {
                  weakSelf.callBack(_readerViewController.maxReadPage);
              }
          }
         
      }];
        
    }
}



#pragma mark -请求pdf下载网址
//- (void)getPdfUrl{
//    
////    "pdfName": "20160526152414_70164695-113d-4634-acbb-2fd99ebed9d4.pdf",
////    "pdfUrl": "http://exam.hulijia365.com:80/scmcstudy/upload/sdimg/20160526152414_70164695-113d-4634-acbb-2fd99ebed9d4.pdf",
////    "studiedSeqNum": 28
//    
////    [self wsj_showLodingGif];
//    
//   
//    
//    cwqHud(self.view);
//   
//    
//    
//    NSMutableDictionary *params =[NSMutableDictionary dictionary];
//    params[@"tblStudyDataId"] =self.course.id;
//    params[@"userId"] =HEL_USERID;
//    weakSelf_define;
//    [[HELNetworkManager sharedMg] GET:kDownloadPdf parameters:params success:^(NSDictionary * responseObject) {
////        [weakSelf wsj_hideLodingGif];
//        [hud hideAnimated:YES];
//        if (responseObject[@"exception"]) {
//             cwqHudRequestError(responseObject[@"exception"]);
//            [weakSelf.navigationController popViewControllerAnimated:YES];
//        }
//        if (responseObject[@"pdfUrl"]) {
//          
//            
//            NSNumber *page =  [HELPDFfileCacheTool getLastPageFromKey:weakSelf.course.pdfName];
//            if (page) {
//               
//                weakSelf.studiedSeqNum =MAX([page integerValue], [responseObject[@"studiedSeqNum"] integerValue]);
//            }else{
//                weakSelf.studiedSeqNum =[responseObject[@"studiedSeqNum"] integerValue];
//            }
//            //更新本地进度
//            [HELPDFfileCacheTool saveLastPage:weakSelf.studiedSeqNum withPdfKey:weakSelf.course.pdfName];
//            [weakSelf downPdfFile];
//        }
//        
//    } failure:^(NSString *err) {
////         [weakSelf wsj_hideLodingGif];
//         [hud hideAnimated:YES];
//        cwqHudRequestError(@"下载出错");
//        [weakSelf dismissViewControllerAnimated:YES completion:nil];
//        
//    }];
//    
//    
//}
- (void)dealloc{


}
//
//- (void)downdloadPdfFile{
//    
//    weakSelf_define;
//    __block MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
//    hud.animationType = MBProgressHUDAnimationZoomOut;
//    hud.label.text = @"正在下载...";
//    hud.progress = 0;
//    [hud showAnimated:YES];
//
//   
//    //下载放置的位置
//   NSString *cachesPath= [JFFileManager documentsDirectory];
//
// 
//   NSString *downDesPath =[cachesPath stringByAppendingPathComponent:self.pdfName];
//
//    JCDownloadItem *downloadItem = [[JCDownloadItem alloc] init];
//    downloadItem.downloadUrl = self.urlStr;
//    downloadItem.downloadFilePath = downDesPath;
//    
//    self.operation = [JCDownloadOperation operationWithItem:downloadItem];
//    [self.operation startWithProgressBlock:^(NSProgress *progress) {
////        CGFloat i =(progress.completedUnitCount *1.0 )/(progress.totalUnitCount *1.0);
//        CGFloat i = progress.completedUnitCount;
//        CGFloat p =progress.totalUnitCount;
//        hud.progress = (i * p)/p -1;
//        //update progress
//    } completionBlock:^(NSURL *filePath, NSError *error) {
//        //download operation completion, do something
//        [hud hideAnimated:YES];
//        if (error) {
//            alertMessage(error.localizedDescription);
//        }
//        NSString *fullPath = [filePath path];
//        [weakSelf preparePdfWithFilePath:fullPath];
//      
//    }];
//
////    [self.operation pauseDownload];
////    [self.operation removeDownload];
////    [self.operation startDownload];
//
//}
//



- (void)downPdfFile{
    

    NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:self.pdfModel.fileName isMP4:NO];
    if (filePath) {
        [self preparePdfWithFilePath:filePath];
        return ;
    };
    weakSelf_define;
   
   WSJPopview *downSeg = [[WSJPopview sharedWsjPopView] showDownLoadWithCourse:self.pdfModel];
    downSeg.cancelBlock = ^(){
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    };
    downSeg.doneBlock = ^(){
        [weakSelf preparePdfWithFilePath:[HELPDFfileCacheTool getDownloadPathWithPdfName:weakSelf.pdfModel.fileName isMp4:NO]];

    };
    downSeg.failBlock = ^(){
        dispatch_async(dispatch_get_main_queue(), ^{
             [weakSelf dismissViewControllerAnimated:YES completion:nil];
        });
       
    };
 
}

- (void)preparePdfWithFilePath:(NSString *)path{
   
    
    MFDocumentManager * documentManager = [[MFDocumentManager alloc]initWithFileUrl:[NSURL fileURLWithPath:path]];
    _readerViewController = [[ReaderViewController alloc] initWithDocumentManager:documentManager];
    weakSelf_define;
    _readerViewController.dismissBlock = ^{

        [weakSelf backAction];
    };
    [self.view addSubview:_readerViewController.view];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_readerViewController viewWillAppear:animated];
   }

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_readerViewController viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_readerViewController viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_readerViewController viewDidDisappear:animated];
   

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_readerViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_readerViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
